<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="referrer" content="no-referrer">
    <title>无敌爬虫</title>
    <link href="static/css/tailwind.min.css" rel="stylesheet">
    <link href="static/css/font-awesome.min.css" rel="stylesheet">
    <link rel="icon" href="static/jpg/favicon.png" type="image/x-icon">
    <script src="static/js/marked.min.js"></script>
    <script src="static/css/tailwindcss.min.js"></script>
    <script src="static/js/axios.min.js"></script>

    <link href="static/css/index.css" rel="stylesheet">
</head>

<body class="bg-gray-50 dark:bg-gray-900 text-gray-800 dark:text-gray-200 min-h-screen flex flex-col">
    <!-- 顶部导航 -->
    <header class="bg-white dark:bg-gray-900 shadow-sm border-b border-gray-200 dark:border-gray-800 sticky top-0 z-50">
        <div class="container mx-auto px-4 py-3 flex items-center justify-between">
            <div class="flex items-center space-x-2">
                <i class="fa fa-file-text-o text-blue-500 text-2xl"></i>
                <h1
                    class="text-xl font-bold bg-gradient-to-r from-blue-500 to-purple-600 bg-clip-text text-transparent">
                    无敌爬虫-测试</h1>
            </div>
            <div class="flex items-center space-x-4">
                <button id="theme-toggle"
                    class="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors">
                    <i class="fa fa-moon-o dark:hidden"></i>
                    <i class="fa fa-sun-o hidden dark:block"></i>
                </button>
                <button id="help-btn"
                    class="p-2 rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors">
                    <i class="fa fa-question-circle"></i>
                </button>
            </div>
        </div>
    </header>

    <!-- 主要内容区 -->
    <main class="flex-1 container mx-auto p-4 md:p-6 flex flex-col">
        <!-- URL 输入区 -->
        <div class="bg-white dark:bg-gray-900 rounded-xl shadow-md p-4 mb-6">
            <div class="flex items-center mb-3">
                <i class="fa fa-link text-blue-500 mr-2"></i>
                <h2 class="font-semibold">URL 输入</h2>
            </div>
            <div class="flex gap-2">
                <input type="url" id="url-input" placeholder="https://example.com/article"
                    class="flex-1 px-4 py-2 border border-gray-300 dark:border-gray-700 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-800 outline-none transition-all input-focus"
                    value="https://example.com">
                <button id="settings-btn"
                    class="bg-gray-500 hover:bg-gray-500/90 text-white px-4 py-2 rounded-lg transition-all flex items-center gap-1 btn-hover">
                    <i class="fa fa-cog"></i>
                    <span>设置</span>
                </button>
                <button id="fetch-btn"
                    class="bg-blue-500 hover:bg-blue-500/90 text-white px-4 py-2 rounded-lg transition-all flex items-center gap-1 btn-hover">
                    <i class="fa fa-download"></i>
                    <span>执行</span>
                </button>
            </div>
        </div>

        <!-- 状态信息 -->
        <div id="status-container" class="bg-white dark:bg-gray-900 rounded-xl shadow-md p-4 mb-6 hidden">
            <div class="flex items-center mb-2">
                <i id="status-icon" class="mr-2"></i>
                <h3 id="status-title" class="font-medium"></h3>
            </div>
            <p id="status-message" class="text-sm text-gray-600 dark:text-gray-400"></p>
        </div>

        <!-- 结果表格区 -->
        <div
            class="bg-white dark:bg-gray-900 rounded-xl shadow-md border border-gray-200 dark:border-gray-700 overflow-hidden flex-1 flex flex-col">
            <div
                class="px-6 py-4 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800 flex items-center justify-between">
                <div class="flex items-center">
                    <i class="fa fa-table text-green-500 mr-2"></i>
                    <h2 class="font-semibold text-gray-800 dark:text-gray-200">提取结果</h2>
                </div>
                <div class="flex items-center space-x-4">
                    <button id="clear-results-btn"
                        class="hidden px-3 py-1.5 bg-red-50 hover:bg-red-100 text-red-600 text-sm font-medium rounded-lg transition-colors">
                        <i class="fa fa-trash mr-1.5"></i>
                        清空结果
                    </button>
                    <button id="delete-selected-btn"
                        class="hidden px-3 py-1.5 bg-red-50 hover:bg-red-100 text-red-600 text-sm font-medium rounded-lg transition-colors">
                        <i class="fa fa-trash-o mr-1.5"></i>
                        删除选中
                    </button>
                    <div class="text-sm text-gray-500 dark:text-gray-400">
                        共 <span id="result-count">0</span> 条记录
                    </div>
                </div>
            </div>

            <!-- 加载状态覆盖层 -->
            <div id="loading-overlay" class="hidden fixed inset-0 bg-black/20 z-40 flex items-center justify-center">
                <div class="bg-white dark:bg-gray-900 rounded-xl shadow-xl p-6 flex flex-col items-center">
                    <div
                        class="w-12 h-12 border-4 border-gray-200 dark:border-gray-700 border-t-blue-500 rounded-full animate-spin mb-4">
                    </div>
                    <p class="text-gray-500 dark:text-gray-400">正在加载和提取内容...</p>
                </div>
            </div>

            <!-- 错误状态 -->
            <div id="error-indicator" class="hidden py-12 text-center">
                <i class="fa fa-exclamation-triangle text-amber-500 text-4xl mb-4"></i>
                <p id="error-message" class="text-amber-500 mb-2">加载失败</p>
                <p class="text-sm text-gray-600 dark:text-gray-400">请检查URL是否有效或尝试其他链接</p>
            </div>

            <!-- 空状态 -->
            <div id="empty-state" class="py-12 text-center">
                <i class="fa fa-file-text-o text-gray-300 dark:text-gray-600 text-5xl mb-4"></i>
                <p class="text-gray-500 dark:text-gray-400">输入URL并点击"执行"开始提取</p>
            </div>

            <!-- 表格容器 -->
            <div id="table-container" class="table-container hidden overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                    <thead class="bg-gray-50 dark:bg-gray-800">
                        <tr>
                            <th scope="col"
                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider whitespace-nowrap w-10">
                                <input type="checkbox" id="select-all-checkbox"
                                    class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                            </th>
                            <th scope="col"
                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider whitespace-nowrap">
                                标题
                            </th>
                            <th scope="col"
                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider whitespace-nowrap">
                                URL
                            </th>
                            <th scope="col"
                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider whitespace-nowrap">
                                发布时间
                            </th>
                            <th scope="col"
                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider whitespace-nowrap">
                                作者
                            </th>
                            <th scope="col"
                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider whitespace-nowrap">
                                导航
                            </th>
                            <th scope="col"
                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider whitespace-nowrap">
                                正文
                            </th>
                            <th scope="col"
                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider whitespace-nowrap">
                                markdown
                            </th>
                            <th scope="col"
                                class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider whitespace-nowrap">
                                采集时间
                            </th>
                            <th scope="col"
                                class="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider whitespace-nowrap w-32">
                                操作
                            </th>
                        </tr>
                    </thead>
                    <tbody id="results-tbody"
                        class="bg-white dark:bg-gray-900 divide-y divide-gray-200 dark:divide-gray-700">
                        <!-- 结果行将通过JavaScript动态添加 -->
                    </tbody>
                </table>
            </div>
        </div>
    </main>

    <!-- 统一预览模态框 -->
    <div id="preview-modal"
        class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 modal-backdrop z-50 hidden">
        <div
            class="bg-white dark:bg-gray-900 rounded-xl shadow-medium max-w-4xl w-full max-h-[90vh] flex flex-col modal-content">
            <!-- 模态框头部 -->
            <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
                <h3 class="text-lg font-semibold text-gray-800 dark:text-gray-200">内容预览</h3>
                <div class="flex items-center space-x-2">
                    <label class="relative inline-flex items-center cursor-pointer" id="toggle-images-container">
                        <input type="checkbox" id="toggle-images-btn" class="sr-only" checked>
                        <span class="toggle-slider"></span>
                        <span class="ml-3 text-sm font-medium text-gray-900 dark:text-gray-300">显示图片</span>
                    </label>
                    <button id="toggle-markdown-style-btn"
                        class="hidden text-sm px-3 py-1 bg-blue-500 hover:bg-blue-600 text-white rounded-md transition-colors">
                        关闭样式
                    </button>
                    <button id="copy-json-btn"
                        class="hidden text-sm px-3 py-1 bg-blue-500 hover:bg-blue-600 text-white rounded-md transition-colors">
                        复制JSON
                    </button>
                    <button id="close-preview"
                        class="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300 transition-colors">
                        <i class="fa fa-times text-xl"></i>
                    </button>
                </div>
            </div>

            <!-- 选项卡导航 -->
            <div
                class="px-6 py-3 border-b border-gray-200 dark:border-gray-700 flex space-x-1 bg-gray-50 dark:bg-gray-800">
                <button
                    class="preview-tab px-4 py-2 text-sm font-medium rounded-t-lg transition-colors bg-white dark:bg-gray-900 text-blue-600 dark:text-blue-400 border border-gray-200 dark:border-gray-700 border-b-0"
                    data-tab="html">
                    <i class="fa fa-file-code-o mr-1"></i>页面预览
                </button>
                <button
                    class="preview-tab px-4 py-2 text-sm font-medium rounded-t-lg transition-colors text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                    data-tab="markdown">
                    <i class="fa fa-file-text-o mr-1"></i>Markdown预览
                </button>
                <button
                    class="preview-tab px-4 py-2 text-sm font-medium rounded-t-lg transition-colors text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                    data-tab="json">
                    <i class="fa fa-code mr-1"></i>JSON预览
                </button>
            </div>

            <!-- 模态框内容 -->
            <div class="flex-grow overflow-y-auto custom-scrollbar p-6">
                <div id="html-preview-content" class="preview-content preview-html hidden">
                    <!-- HTML内容将在这里显示 -->
                </div>
                <div id="markdown-preview-content" class="preview-content preview-markdown hidden">
                    <!-- Markdown内容将在这里显示 -->
                </div>
                <!-- JSON预览内容 -->
                <div id="json-preview-content" class="preview-content hidden">
                    <pre class="bg-gray-50 dark:bg-gray-800 p-4 rounded-lg text-sm overflow-x-auto">
            <!-- JSON内容将在这里显示 -->
                    </pre>
                </div>
            </div>

            <!-- 模态框底部 -->
            <div class="px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex justify-end">
                <button id="close-preview-btn"
                    class="px-4 py-2 bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 rounded-lg transition-colors">
                    关闭
                </button>
            </div>
        </div>
    </div>

    <!-- 帮助模态框 -->
    <div id="help-modal"
        class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 modal-backdrop z-50 hidden">
        <div class="bg-white rounded-xl shadow-medium max-w-4xl w-full max-h-[90vh] flex flex-col modal-content">
            <div class="px-6 py-4 border-b border-neutral-200 flex items-center justify-between">
                <h3 class="text-lg font-semibold text-neutral-800">使用帮助</h3>
                <button id="close-help" class="text-neutral-500 hover:text-neutral-700 transition-colors">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            <div class="flex-grow overflow-y-auto custom-scrollbar p-6">
                <div class="space-y-6">
                    <div>
                        <h4 class="text-md font-semibold text-neutral-800 mb-2">基本使用</h4>
                        <p class="text-neutral-600">在输入框中输入一个或多个URL，每行一个URL。点击"开始爬取"按钮开始爬取网页内容。</p>
                    </div>
                    <div>
                        <h4 class="text-md font-semibold text-neutral-800 mb-2">高级选项</h4>
                        <ul class="list-disc pl-5 text-neutral-600 space-y-1">
                            <li>爬取深度：设置爬取的链接深度，默认为1</li>
                            <li>超时时间：设置请求超时时间，默认为10秒</li>
                            <li>并发数：设置并发请求数，默认为5</li>
                            <li>最大页面数：设置最大爬取页面数，默认为100</li>
                        </ul>
                    </div>
                    <div>
                        <h4 class="text-md font-semibold text-neutral-800 mb-2">导出选项</h4>
                        <p class="text-neutral-600">爬取完成后，可以导出为以下格式：</p>
                        <ul class="list-disc pl-5 text-neutral-600 space-y-1">
                            <li>JSON格式：包含所有爬取数据的结构化格式</li>
                            <li>CSV格式：适合在Excel等软件中打开的表格格式</li>
                            <li>Markdown格式：适合在Markdown编辑器中查看的格式</li>
                        </ul>
                    </div>
                    <div>
                        <h4 class="text-md font-semibold text-neutral-800 mb-2">快捷键</h4>
                        <ul class="list-disc pl-5 text-neutral-600 space-y-1">
                            <li>Ctrl+Enter：开始爬取</li>
                            <li>Ctrl+S：导出结果</li>
                            <li>Esc：关闭当前模态框</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 设置模态框 -->
    <div id="settings-modal"
        class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 modal-backdrop z-50 hidden">
        <div
            class="bg-white dark:bg-gray-900 rounded-xl shadow-medium max-w-4xl w-full max-h-[90vh] flex flex-col modal-content">
            <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
                <h3 class="text-lg font-semibold text-gray-800 dark:text-gray-200">爬虫设置</h3>
                <button id="close-settings"
                    class="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300 transition-colors">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            <div class="flex-grow overflow-y-auto custom-scrollbar p-6">
                <div class="space-y-6">
                    <!-- 域名选择器列表 -->
                    <div>
                        <h4 class="text-md font-semibold text-gray-800 dark:text-gray-200 mb-2 flex items-center">
                            <i class="fa fa-globe mr-2 text-blue-500"></i>
                            域名选择器配置
                        </h4>
                        <p class="text-sm text-gray-600 dark:text-gray-400 mb-3">为不同域名配置选择器规则，爬虫将根据URL域名自动匹配对应的选择器配置</p>

                        <!-- 域名选择器表格 -->
                        <div class="overflow-x-auto">
                            <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                                <thead class="bg-gray-50 dark:bg-gray-800">
                                    <tr>
                                        <th scope="col"
                                            class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                                            域名
                                        </th>
                                        <th scope="col"
                                            class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                                            选择器配置
                                        </th>
                                        <th scope="col"
                                            class="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                                            操作
                                        </th>
                                    </tr>
                                </thead>
                                <tbody id="domain-selectors-tbody"
                                    class="bg-white dark:bg-gray-900 divide-y divide-gray-200 dark:divide-gray-700">
                                    <!-- 域名选择器行将通过JavaScript动态添加 -->
                                </tbody>
                            </table>
                        </div>

                        <!-- 添加新域名按钮 -->
                        <div class="mt-4 flex justify-end">
                            <button id="add-domain-selector"
                                class="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-colors">
                                <i class="fa fa-plus mr-2"></i>添加域名配置
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex justify-end space-x-3">
                <button id="reset-settings"
                    class="px-4 py-2 bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 rounded-lg transition-colors">
                    重置
                </button>
                <button id="save-settings"
                    class="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-colors">
                    保存设置
                </button>
            </div>
        </div>
    </div>

    <!-- 域名选择器编辑模态框 -->
    <div id="domain-selector-modal"
        class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 modal-backdrop z-50 hidden">
        <div
            class="bg-white dark:bg-gray-900 rounded-xl shadow-medium max-w-4xl w-full max-h-[90vh] flex flex-col modal-content">
            <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
                <h3 class="text-lg font-semibold text-gray-800 dark:text-gray-200">编辑域名选择器</h3>
                <button id="close-domain-selector"
                    class="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300 transition-colors">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            <div class="flex-grow overflow-y-auto custom-scrollbar p-6">
                <div class="space-y-6">
                    <!-- 域名设置 -->
                    <div>
                        <h4 class="text-md font-semibold text-gray-800 dark:text-gray-200 mb-2 flex items-center">
                            <i class="fa fa-globe mr-2 text-blue-500"></i>
                            域名
                        </h4>
                        <input type="text" id="domain-input" placeholder="例如: www.example.com"
                            class="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-800 outline-none">
                        <p class="text-sm text-gray-600 dark:text-gray-400 mt-2">请输入网站的域名，不包含协议和路径</p>
                    </div>

                    <!-- 时间选择器设置 -->
                    <div>
                        <h4 class="text-md font-semibold text-gray-800 dark:text-gray-200 mb-2 flex items-center">
                            <i class="fa fa-clock-o mr-2 text-blue-500"></i>
                            时间选择器 (time_selectors)
                        </h4>
                        <p class="text-sm text-gray-600 dark:text-gray-400 mb-3">用于提取文章发布时间的CSS选择器或XPath表达式</p>
                        <div id="edit-time-selectors-container" class="space-y-2">
                            <!-- 动态添加的选择器输入框将在这里 -->
                        </div>
                        <button id="edit-add-time-selector"
                            class="mt-2 px-3 py-1 bg-blue-50 hover:bg-blue-100 text-blue-600 text-sm rounded-md transition-colors">
                            <i class="fa fa-plus mr-1"></i>添加选择器
                        </button>
                    </div>

                    <!-- 内容选择器设置 -->
                    <div>
                        <h4 class="text-md font-semibold text-gray-800 dark:text-gray-200 mb-2 flex items-center">
                            <i class="fa fa-file-text-o mr-2 text-green-500"></i>
                            内容选择器 (content_selectors)
                        </h4>
                        <p class="text-sm text-gray-600 dark:text-gray-400 mb-3">用于提取文章正文内容的CSS选择器或XPath表达式</p>
                        <div id="edit-content-selectors-container" class="space-y-2">
                            <!-- 动态添加的选择器输入框将在这里 -->
                        </div>
                        <button id="edit-add-content-selector"
                            class="mt-2 px-3 py-1 bg-blue-50 hover:bg-blue-100 text-blue-600 text-sm rounded-md transition-colors">
                            <i class="fa fa-plus mr-1"></i>添加选择器
                        </button>
                    </div>

                    <!-- 导航选择器设置 -->
                    <div>
                        <h4 class="text-md font-semibold text-gray-800 dark:text-gray-200 mb-2 flex items-center">
                            <i class="fa fa-sitemap mr-2 text-purple-500"></i>
                            导航选择器 (nav_selectors)
                        </h4>
                        <p class="text-sm text-gray-600 dark:text-gray-400 mb-3">用于提取网站导航路径的CSS选择器或XPath表达式</p>
                        <div id="edit-nav-selectors-container" class="space-y-2">
                            <!-- 动态添加的选择器输入框将在这里 -->
                        </div>
                        <button id="edit-add-nav-selector"
                            class="mt-2 px-3 py-1 bg-blue-50 hover:bg-blue-100 text-blue-600 text-sm rounded-md transition-colors">
                            <i class="fa fa-plus mr-1"></i>添加选择器
                        </button>
                    </div>

                    <!-- 作者选择器设置 -->
                    <div>
                        <h4 class="text-md font-semibold text-gray-800 dark:text-gray-200 mb-2 flex items-center">
                            <i class="fa fa-user-o mr-2 text-orange-500"></i>
                            作者选择器 (author_selectors)
                        </h4>
                        <p class="text-sm text-gray-600 dark:text-gray-400 mb-3">用于提取文章作者的CSS选择器或XPath表达式</p>
                        <div id="edit-author-selectors-container" class="space-y-2">
                            <!-- 动态添加的选择器输入框将在这里 -->
                        </div>
                        <button id="edit-add-author-selector"
                            class="mt-2 px-3 py-1 bg-blue-50 hover:bg-blue-100 text-blue-600 text-sm rounded-md transition-colors">
                            <i class="fa fa-plus mr-1"></i>添加选择器
                        </button>
                    </div>

                    <!-- 预设选择器 -->
                    <div>
                        <h4 class="text-md font-semibold text-gray-800 dark:text-gray-200 mb-2 flex items-center">
                            <i class="fa fa-magic mr-2 text-indigo-500"></i>
                            预设选择器
                        </h4>
                        <p class="text-sm text-gray-600 dark:text-gray-400 mb-3">选择网站预设的选择器配置</p>
                        <select id="edit-preset-selector"
                            class="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-800 outline-none">
                            <option value="">-- 选择预设 --</option>
                            <option value="mp.weixin.qq.com">微信公众号 (mp.weixin.qq.com)</option>
                            <option value="news.qq.com">腾讯新闻 (news.qq.com)</option>
                            <option value="www.163.com">网易新闻 (www.163.com)</option>
                            <option value="news.sina.com.cn">新浪新闻 (news.sina.com.cn)</option>
                            <option value="www.thepaper.cn">澎湃新闻 (www.thepaper.cn)</option>
                            <option value="news.cctv.com">央视新闻 (news.cctv.com)</option>
                            <option value="news.ifeng.com">凤凰新闻 (news.ifeng.com)</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex justify-end space-x-3">
                <button id="cancel-domain-selector"
                    class="px-4 py-2 bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 rounded-lg transition-colors">
                    取消
                </button>
                <button id="save-domain-selector"
                    class="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-colors">
                    保存
                </button>
            </div>
        </div>
    </div>

    <!-- 底部信息 -->
    <footer class="bg-white dark:bg-gray-900 border-t border-gray-200 dark:border-gray-800 py-4">
        <div class="container mx-auto px-4 text-center text-sm text-gray-500 dark:text-gray-400">
            <p>Powered by 无敌爬虫</p>
        </div>
    </footer>

    <script>
        // 初始化Markdown解析库（修复3：使用专业库替代手动正则）
        marked.setOptions({
            breaks: true, // 支持换行
            gfm: true,    // 支持GitHub Flavored Markdown
            sanitize: true // 过滤危险HTML，防止XSS
        });

        // 全局变量
        let resultsData = [];

        // 保存数据到localStorage
        function saveDataToLocalStorage() {
            try {
                localStorage.setItem('crawlerResults', JSON.stringify(resultsData));
                console.log('数据已保存到localStorage');
            } catch (error) {
                console.error('保存数据到localStorage失败:', error);
                showStatus('error', '保存失败', '无法保存数据到本地存储');
            }
        }

        // 从localStorage加载数据
        function loadDataFromLocalStorage() {
            try {
                const savedData = localStorage.getItem('crawlerResults');
                if (savedData) {
                    resultsData = JSON.parse(savedData);

                    // 为没有唯一ID的数据生成唯一ID
                    resultsData.forEach(item => {
                        if (!item.id) {
                            // 基于采集时间和URL生成唯一ID
                            const timeStr = item.time ? item.time.toString() : Date.now().toString();
                            const urlStr = item.url || '';
                            // 使用btoa哈希生成16位ID
                            const hash = btoa(timeStr + urlStr).substring(0, 16);
                            item.id = hash;
                        }
                    });

                    console.log('从localStorage加载了', resultsData.length, '条数据');
                    return true;
                }
                return false;
            } catch (error) {
                console.error('从localStorage加载数据失败:', error);
                showStatus('error', '加载失败', '无法从本地存储加载数据');
                return false;
            }
        }

        // DOM 元素
        const urlInput = document.getElementById('url-input');
        const fetchBtn = document.getElementById('fetch-btn');
        const settingsBtn = document.getElementById('settings-btn');
        const statusContainer = document.getElementById('status-container');
        const statusIcon = document.getElementById('status-icon');
        const statusTitle = document.getElementById('status-title');
        const statusMessage = document.getElementById('status-message');
        const themeToggle = document.getElementById('theme-toggle');
        const helpBtn = document.getElementById('help-btn');
        const helpModal = document.getElementById('help-modal');
        const closeHelp = document.getElementById('close-help');
        const loadingOverlay = document.getElementById('loading-overlay');
        const errorIndicator = document.getElementById('error-indicator');
        const errorMessage = document.getElementById('error-message');
        const emptyState = document.getElementById('empty-state');
        const tableContainer = document.getElementById('table-container');
        const resultsTbody = document.getElementById('results-tbody');
        const resultCount = document.getElementById('result-count');
        const clearResultsBtn = document.getElementById('clear-results-btn');
        const deleteSelectedBtn = document.getElementById('delete-selected-btn');
        const selectAllCheckbox = document.getElementById('select-all-checkbox');

        // 设置模态框元素
        const settingsModal = document.getElementById('settings-modal');
        const closeSettings = document.getElementById('close-settings');
        const saveSettings = document.getElementById('save-settings');
        const resetSettings = document.getElementById('reset-settings');
        const presetSelector = document.getElementById('edit-preset-selector');

        // 选择器容器
        const timeSelectorsContainer = document.getElementById('edit-time-selectors-container');
        const contentSelectorsContainer = document.getElementById('edit-content-selectors-container');
        const navSelectorsContainer = document.getElementById('edit-nav-selectors-container');
        const authorSelectorsContainer = document.getElementById('edit-author-selectors-container');

        // 添加选择器按钮
        const addTimeSelector = document.getElementById('edit-add-time-selector');
        const addContentSelector = document.getElementById('edit-add-content-selector');
        const addNavSelector = document.getElementById('edit-add-nav-selector');
        const addAuthorSelector = document.getElementById('edit-add-author-selector');

        // 预览模态框元素
        const previewModal = document.getElementById('preview-modal');
        const closePreview = document.getElementById('close-preview');
        const closePreviewBtn = document.getElementById('close-preview-btn');
        const htmlPreviewContent = document.getElementById('html-preview-content');
        const markdownPreviewContent = document.getElementById('markdown-preview-content');
        const jsonPreviewContent = document.getElementById('json-preview-content');
        const toggleImagesBtn = document.getElementById('toggle-images-btn');
        const toggleImagesContainer = document.getElementById('toggle-images-container');
        const toggleMarkdownStyleBtn = document.getElementById('toggle-markdown-style-btn');
        const copyJsonBtn = document.getElementById('copy-json-btn');

        // 预览选项卡
        const previewTabs = document.querySelectorAll('.preview-tab');
        const previewContents = document.querySelectorAll('.preview-content');

        // 当前预览数据
        let currentPreviewData = null;

        // 初始化主题
        if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
            document.documentElement.classList.add('dark');
        } else {
            document.documentElement.classList.remove('dark');
        }

        // 页面加载时从localStorage恢复数据
        document.addEventListener('DOMContentLoaded', () => {
            // 尝试从localStorage加载数据
            const hasSavedData = loadDataFromLocalStorage();

            if (hasSavedData && resultsData.length > 0) {
                // 显示表格
                tableContainer.classList.remove('hidden');
                emptyState.classList.add('hidden');

                // 显示清空按钮
                clearResultsBtn.classList.remove('hidden');

                // 添加所有保存的数据到表格
                resultsData.forEach((item, index) => {
                    addResultRow(item, index);
                });

                // 更新结果计数
                resultCount.textContent = resultsData.length;

                showStatus('info', '数据恢复', `已从本地存储恢复 ${resultsData.length} 条记录`);
            }
        });

        // 主题切换
        themeToggle.addEventListener('click', () => {
            document.documentElement.classList.toggle('dark');
            localStorage.theme = document.documentElement.classList.contains('dark') ? 'dark' : 'light';
        });

        // 帮助模态框
        helpBtn.addEventListener('click', () => {
            helpModal.classList.remove('hidden');
            helpModal.classList.add('flex');
        });

        closeHelp.addEventListener('click', () => {
            helpModal.classList.add('hidden');
            helpModal.classList.remove('flex');
        });

        helpModal.addEventListener('click', (e) => {
            if (e.target === helpModal) {
                helpModal.classList.add('hidden');
                helpModal.classList.remove('flex');
            }
        });

        // 设置模态框
        settingsBtn.addEventListener('click', () => {
            loadSettings();
            settingsModal.classList.remove('hidden');
            settingsModal.classList.add('flex');
        });

        closeSettings.addEventListener('click', () => {
            settingsModal.classList.add('hidden');
            settingsModal.classList.remove('flex');
        });

        settingsModal.addEventListener('click', (e) => {
            if (e.target === settingsModal) {
                settingsModal.classList.add('hidden');
                settingsModal.classList.remove('flex');
            }
        });

        // 预设选择器变化事件
        presetSelector.addEventListener('change', (e) => {
            const selectedPreset = e.target.value;
            if (selectedPreset) {
                loadPresetSettings(selectedPreset);
            }
        });

        // 添加选择器按钮事件
        addTimeSelector.addEventListener('click', () => {
            addSelectorInput(timeSelectorsContainer, 'time_selectors');
        });

        addContentSelector.addEventListener('click', () => {
            addSelectorInput(contentSelectorsContainer, 'content_selectors');
        });

        addNavSelector.addEventListener('click', () => {
            addSelectorInput(navSelectorsContainer, 'nav_selectors');
        });

        addAuthorSelector.addEventListener('click', () => {
            addSelectorInput(authorSelectorsContainer, 'author_selectors');
        });

        // 保存和重置设置按钮事件
        saveSettings.addEventListener('click', () => {
            saveCurrentSettings();
            settingsModal.classList.add('hidden');
            settingsModal.classList.remove('flex');
            showStatus('success', '设置已保存', '您的选择器配置已成功保存。');
        });

        resetSettings.addEventListener('click', () => {
            if (confirm('确定要重置所有设置吗？')) {
                resetAllSettings();
                showStatus('info', '设置已重置', '所有选择器配置已重置为默认值。');
            }
        });

        // 预览模态框关闭事件
        closePreview.addEventListener('click', () => {
            previewModal.classList.add('hidden');
            previewModal.classList.remove('flex');
        });

        closePreviewBtn.addEventListener('click', () => {
            previewModal.classList.add('hidden');
            previewModal.classList.remove('flex');
        });

        previewModal.addEventListener('click', (e) => {
            if (e.target === previewModal) {
                previewModal.classList.add('hidden');
                previewModal.classList.remove('flex');
            }
        });

        // 预览选项卡切换
        previewTabs.forEach(tab => {
            tab.addEventListener('click', () => {
                const tabName = tab.getAttribute('data-tab');

                // 更新选项卡样式
                previewTabs.forEach(t => {
                    t.classList.remove('bg-white', 'dark:bg-gray-900', 'text-blue-600', 'dark:text-blue-400', 'border', 'border-gray-200', 'dark:border-gray-700', 'border-b-0');
                    t.classList.add('text-gray-500', 'hover:text-gray-700', 'dark:text-gray-400', 'dark:hover:text-gray-300', 'hover:bg-gray-100', 'dark:hover:bg-gray-700');
                });

                tab.classList.remove('text-gray-500', 'hover:text-gray-700', 'dark:text-gray-400', 'dark:hover:text-gray-300', 'hover:bg-gray-100', 'dark:hover:bg-gray-700');
                tab.classList.add('bg-white', 'dark:bg-gray-900', 'text-blue-600', 'dark:text-blue-400', 'border', 'border-gray-200', 'dark:border-gray-700', 'border-b-0');

                // 更新内容显示
                previewContents.forEach(content => {
                    content.classList.add('hidden');
                });
                // 显示对应内容
                if (tabName === 'html') {
                    showHtmlPreview(currentPreviewData)
                } else if (tabName === 'markdown') {
                    showMarkdownPreview(currentPreviewData)
                } else if (tabName === 'json') {
                    showJsonPreview(currentPreviewData)
                }
            });
        });
        function toggleHtmlPreview(event) {
            const isImagesVisible = toggleImagesBtn.checked;

            if (!isImagesVisible) {
                // 隐藏所有图片
                const images = htmlPreviewContent.querySelectorAll('img');
                images.forEach(img => {
                    // 保存原始display属性
                    if (!img.dataset.originalDisplay) {
                        img.dataset.originalDisplay = img.style.display || '';
                    }
                    img.style.display = 'none';
                });
            } else {
                // 恢复所有图片
                const images = htmlPreviewContent.querySelectorAll('img');
                images.forEach(img => {
                    // 恢复原始display属性
                    if (img.dataset.originalDisplay !== undefined) {
                        img.style.display = img.dataset.originalDisplay;
                    } else {
                        img.style.display = '';
                    }
                });
            }
        }

        // 无图模式按钮事件监听器
        toggleImagesBtn.addEventListener('change', toggleHtmlPreview);

        // Markdown样式开关事件监听器
        toggleMarkdownStyleBtn.addEventListener('click', () => {
            if (toggleMarkdownStyleBtn.textContent === '关闭样式') {
                // 显示原始Markdown内容
                if (markdownPreviewContent.originalMarkdown) {
                    markdownPreviewContent.innerHTML = `<pre class="whitespace-pre-wrap text-sm">${markdownPreviewContent.originalMarkdown}</pre>`;
                } else if (markdownPreviewContent.originalContent) {
                    const plainText = markdownPreviewContent.originalContent.replace(/<[^>]*>/g, ' ');
                    markdownPreviewContent.innerHTML = `<pre class="whitespace-pre-wrap text-sm">${plainText}</pre>`;
                }

                // 更新按钮状态
                toggleMarkdownStyleBtn.textContent = '开启样式';
                toggleMarkdownStyleBtn.classList.remove('bg-blue-500', 'hover:bg-blue-600');
                toggleMarkdownStyleBtn.classList.add('bg-green-500', 'hover:bg-green-600');
            } else {
                // 显示带样式的Markdown内容（修复5：重新用marked解析）
                if (markdownPreviewContent.originalMarkdown) {
                    markdownPreviewContent.innerHTML = marked.parse(markdownPreviewContent.originalMarkdown);
                } else if (markdownPreviewContent.originalContent) {
                    const plainText = markdownPreviewContent.originalContent.replace(/<[^>]*>/g, ' ');
                    markdownPreviewContent.innerHTML = marked.parse(plainText);
                }

                // 更新按钮状态
                toggleMarkdownStyleBtn.textContent = '关闭样式';
                toggleMarkdownStyleBtn.classList.remove('bg-green-500', 'hover:bg-green-600');
                toggleMarkdownStyleBtn.classList.add('bg-blue-500', 'hover:bg-blue-600');
            }
        });

        // 复制JSON按钮事件监听器
        copyJsonBtn.addEventListener('click', () => {
            if (currentPreviewData) {
                try {
                    // 格式化JSON数据
                    const formattedJson = JSON.stringify(currentPreviewData, null, 2);

                    // 复制到剪贴板
                    navigator.clipboard.writeText(formattedJson).then(() => {
                        showStatus('success', '复制成功', 'JSON数据已复制到剪贴板');
                    }).catch(err => {
                        showStatus('error', '复制失败', `无法复制JSON数据: ${err.message}`);
                    });
                } catch (error) {
                    showStatus('error', 'JSON格式化错误', `无法格式化JSON数据: ${error.message}`);
                }
            }
        });

        // 显示JSON预览的函数
        function showJsonPreview(jsonData) {
            console.log(777)
            try {
                // 尝试解析JSON数据（如果已经是对象，则直接使用）
                const parsedData = typeof jsonData === 'string' ? JSON.parse(jsonData) : jsonData;

                // 格式化JSON数据
                const formattedJson = JSON.stringify(parsedData, null, 2);

                // 设置JSON内容
                const jsonPreElement = jsonPreviewContent.querySelector('pre');
                jsonPreElement.textContent = formattedJson;

                // 保存当前预览数据
                currentPreviewData = parsedData;

                // 显示模态框
                previewModal.classList.remove('hidden');
                previewModal.classList.add('flex');

                // 切换到JSON选项卡
                const htmlTab = document.querySelector('.preview-tab[data-tab="html"]');
                htmlTab.classList.remove('bg-white', 'dark:bg-gray-900', 'text-blue-600', 'dark:text-blue-400', 'border', 'border-gray-200', 'dark:border-gray-700', 'border-b-0');
                htmlTab.classList.add('text-gray-500', 'hover:text-gray-700', 'dark:text-gray-400', 'dark:hover:text-gray-300', 'hover:bg-gray-100', 'dark:hover:bg-gray-700');

                const markdownTab = document.querySelector('.preview-tab[data-tab="markdown"]');
                markdownTab.classList.remove('bg-white', 'dark:bg-gray-900', 'text-blue-600', 'dark:text-blue-400', 'border', 'border-gray-200', 'dark:border-gray-700', 'border-b-0');
                markdownTab.classList.add('text-gray-500', 'hover:text-gray-700', 'dark:text-gray-400', 'dark:hover:text-gray-300', 'hover:bg-gray-100', 'dark:hover:bg-gray-700');

                const jsonTab = document.querySelector('.preview-tab[data-tab="json"]');
                jsonTab.classList.add('bg-white', 'dark:bg-gray-900', 'text-blue-600', 'dark:text-blue-400', 'border', 'border-gray-200', 'dark:border-gray-700', 'border-b-0');
                jsonTab.classList.remove('text-gray-500', 'hover:text-gray-700', 'dark:text-gray-400', 'dark:hover:text-gray-300', 'hover:bg-gray-100', 'dark:hover:bg-gray-700');

                // 显示JSON内容，隐藏其他内容
                htmlPreviewContent.classList.add('hidden');
                markdownPreviewContent.classList.add('hidden');
                jsonPreviewContent.classList.remove('hidden');

                // 更新按钮可见性
                toggleImagesContainer.classList.add('hidden');
                toggleMarkdownStyleBtn.classList.add('hidden');
                copyJsonBtn.classList.remove('hidden');
            } catch (error) {
                showStatus('error', 'JSON解析错误', `无法解析JSON数据: ${error.message}`);
            }
        }

        // 显示状态消息
        function showStatus(type, title, message) {
            statusContainer.classList.remove('hidden');

            // 设置图标和颜色
            if (type === 'success') {
                statusIcon.className = 'fa fa-check-circle text-green-500';
                statusTitle.className = 'font-medium text-green-500';
            } else if (type === 'error') {
                statusIcon.className = 'fa fa-exclamation-circle text-red-500';
                statusTitle.className = 'font-medium text-red-500';
            } else if (type === 'info') {
                statusIcon.className = 'fa fa-info-circle text-blue-500';
                statusTitle.className = 'font-medium text-blue-500';
            }

            statusTitle.textContent = title;
            statusMessage.textContent = message;

            // 3秒后自动隐藏
            setTimeout(() => {
                statusContainer.classList.add('hidden');
            }, 3000);
        }

        // 添加结果行到表格
        function addResultRow(data, index) {
            const row = document.createElement('tr');
            row.className = 'table-row-hover transition-colors';

            // 为每条数据生成基于采集时间和URL的唯一ID
            let uniqueId;
            if (data.id) {
                // 如果数据已有ID，直接使用
                uniqueId = data.id;
            } else {
                // 否则根据采集时间和URL生成唯一ID
                const timeStr = data.crawl_time || new Date().toISOString();
                const urlStr = data.url || '';
                // 使用时间和URL的简单哈希生成ID
                uniqueId = 'id-' + btoa(timeStr + urlStr).replace(/[^a-zA-Z0-9]/g, '').substring(0, 16);
                // 将生成的ID保存到数据对象中
                data.id = uniqueId;
            }

            // 为每行添加唯一ID，用于标识数据
            const rowId = 'row-' + uniqueId;
            row.id = rowId;

            // 保存数据索引，用于删除操作
            const dataIndex = index !== undefined ? index : resultsData.length;
            row.dataset.dataIndex = dataIndex;
            row.dataset.uniqueId = uniqueId; // 保存唯一ID

            // 复选框单元格
            const checkboxCell = document.createElement('td');
            checkboxCell.className = 'px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400';

            const checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.className = 'row-checkbox rounded border-gray-300 text-blue-600 focus:ring-blue-500';
            checkbox.dataset.rowId = rowId;
            checkbox.dataset.dataIndex = dataIndex; // 保存数据索引
            checkbox.dataset.uniqueId = uniqueId; // 保存唯一ID

            checkboxCell.appendChild(checkbox);

            // 标题单元格
            const titleCell = document.createElement('td');
            titleCell.className = 'px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100 max-w-xs truncate';
            titleCell.textContent = data.title || '无标题';
            titleCell.title = data.title || '无标题';

            // URL单元格
            const urlCell = document.createElement('td');
            urlCell.className = 'px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400 max-w-xs truncate';
            const urlLink = document.createElement('a');
            urlLink.href = data.url || '#';
            urlLink.target = '_blank';
            urlLink.className = 'text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300';
            urlLink.textContent = data.url || '无URL';
            urlLink.title = data.url || '无URL';
            urlCell.appendChild(urlLink);
            // 作者单元格
            const authorCell = document.createElement('td');
            authorCell.className = 'px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400 max-w-xs truncate';
            authorCell.textContent = data.byline || "未知"
            console.log(666)
            // 发布时间单元格
            const publishTimeCell = document.createElement('td');
            publishTimeCell.className = 'px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400';
            // 格式化时间
            let timeText = '未知';
            if (data.published_time) {
                try {
                    const date = new Date(data.published_time);
                    timeText = date.toLocaleString('zh-CN', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit',
                        second: '2-digit'
                    });
                } catch (e) {
                    timeText = data.published_time;
                }
            }
            publishTimeCell.textContent = timeText;

            // 导航单元格
            const navigationCell = document.createElement('td');
            navigationCell.className = 'px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400';
            navigationCell.textContent = data.navigation || '无导航';

            // 正文单元格
            const contentCell = document.createElement('td');
            contentCell.className = 'px-6 py-4 text-sm text-gray-700 dark:text-gray-300 max-w-xs truncate';
            // 创建简短的内容预览
            let contentText = '';
            if (data.content) {
                // 移除HTML标签并截取前50个字符
                contentText = data.content.replace(/<[^>]*>/g, '').substring(0, 50) + '...';
            } else {
                contentText = '无正文';
            }
            contentCell.textContent = contentText;
            // 添加点击事件，切换到正文内容预览
            contentCell.style.cursor = 'pointer';
            contentCell.title = '点击查看正文内容';
            contentCell.addEventListener('click', () => {
                showHtmlPreview(data);
            });

            // Markdown单元格
            const markdownCell = document.createElement('td');
            markdownCell.className = 'px-6 py-4 text-sm text-gray-700 dark:text-gray-300 max-w-xs truncate';
            // 创建简短的Markdown预览
            let markdownText = '';
            if (data.markdown) {
                // 移除Markdown标记并截取前50个字符
                markdownText = data.markdown.replace(/[#*`\[\]()]/g, '').substring(0, 50) + '...';
            } else {
                markdownText = '无Markdown';
            }
            markdownCell.textContent = markdownText;
            // 添加点击事件，切换到Markdown预览
            markdownCell.style.cursor = 'pointer';
            markdownCell.title = '点击查看Markdown内容';
            markdownCell.addEventListener('click', () => {
                showMarkdownPreview(data);
            });

            // 采集时间单元格
            const crawlTimeCell = document.createElement('td');
            crawlTimeCell.className = 'px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400';
            // 格式化采集时间
            let crawlTimeText = '未知';
            if (data.crawl_time) {
                try {
                    const date = new Date(data.crawl_time);
                    crawlTimeText = date.toLocaleString('zh-CN', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit',
                        second: '2-digit'
                    });
                } catch (e) {
                    crawlTimeText = data.crawl_time;
                }
            } else {
                // 如果没有crawl_time字段，使用当前时间
                crawlTimeText = new Date().toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit'
                });
            }
            crawlTimeCell.textContent = crawlTimeText;

            // 操作单元格
            const actionsCell = document.createElement('td');
            actionsCell.className = 'px-6 py-4 whitespace-nowrap text-right text-sm font-medium';

            // 创建预览按钮
            const previewBtn = document.createElement('button');
            previewBtn.className = 'text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300 transition-colors';
            previewBtn.innerHTML = '<i class="fa fa-eye mr-1"></i>预览';
            previewBtn.addEventListener('click', () => {
                // 显示预览模态框
                if (data.content_type === 'html') {
                    showHtmlPreview(data);
                } else if (data.content_type === 'markdown') {
                    showMarkdownPreview(data);
                } else {
                    // 默认显示JSON预览
                    showJsonPreview(data);
                }
            });

            actionsCell.appendChild(previewBtn);

            // 添加单元格到行
            row.appendChild(checkboxCell);
            row.appendChild(titleCell);
            row.appendChild(urlCell);

            row.appendChild(publishTimeCell);
            row.appendChild(authorCell)
            row.appendChild(navigationCell);
            row.appendChild(contentCell);
            row.appendChild(markdownCell);
            row.appendChild(crawlTimeCell);
            row.appendChild(actionsCell);

            // 添加行到表格
            resultsTbody.appendChild(row);

            // 更新结果计数
            resultCount.textContent = resultsData.length;
        }

        // 显示HTML预览
        function showHtmlPreview(data) {
            // 保存原始内容
            const content = data.content || '无内容';
            htmlPreviewContent.originalContent = content;
            htmlPreviewContent.innerHTML = content;

            // 重置无图模式按钮状态
            toggleImagesBtn.textContent = '无图模式';
            toggleImagesBtn.classList.remove('bg-green-500', 'hover:bg-green-600');
            toggleImagesBtn.classList.add('bg-blue-500', 'hover:bg-blue-600');

            // 保存当前预览数据
            currentPreviewData = data;

            // 显示模态框
            previewModal.classList.remove('hidden');
            previewModal.classList.add('flex');

            // 切换到HTML选项卡
            const htmlTab = document.querySelector('.preview-tab[data-tab="html"]');
            htmlTab.classList.add('bg-white', 'dark:bg-gray-900', 'text-blue-600', 'dark:text-blue-400', 'border', 'border-gray-200', 'dark:border-gray-700', 'border-b-0');
            htmlTab.classList.remove('text-gray-500', 'hover:text-gray-700', 'dark:text-gray-400', 'dark:hover:text-gray-300', 'hover:bg-gray-100', 'dark:hover:bg-gray-700');

            const markdownTab = document.querySelector('.preview-tab[data-tab="markdown"]');
            markdownTab.classList.remove('bg-white', 'dark:bg-gray-900', 'text-blue-600', 'dark:text-blue-400', 'border', 'border-gray-200', 'dark:border-gray-700', 'border-b-0');
            markdownTab.classList.add('text-gray-500', 'hover:text-gray-700', 'dark:text-gray-400', 'dark:hover:text-gray-300', 'hover:bg-gray-100', 'dark:hover:bg-gray-700');

            const jsonTab = document.querySelector('.preview-tab[data-tab="json"]');
            jsonTab.classList.remove('bg-white', 'dark:bg-gray-900', 'text-blue-600', 'dark:text-blue-400', 'border', 'border-gray-200', 'dark:border-gray-700', 'border-b-0');
            jsonTab.classList.add('text-gray-500', 'hover:text-gray-700', 'dark:text-gray-400', 'dark:hover:text-gray-300', 'hover:bg-gray-100', 'dark:hover:bg-gray-700');

            // 显示HTML内容，隐藏其他内容
            htmlPreviewContent.classList.remove('hidden');
            markdownPreviewContent.classList.add('hidden');
            jsonPreviewContent.classList.add('hidden');

            // 更新按钮可见性
            toggleImagesBtn.classList.remove('hidden');
            toggleMarkdownStyleBtn.classList.add('hidden');
            copyJsonBtn.classList.add('hidden');
        }

        // 显示Markdown预览
        function showMarkdownPreview(data) {
            // 保存原始Markdown内容
            const markdown = data.markdown || '';
            const content = data.content || '无内容';
            markdownPreviewContent.originalMarkdown = markdown;
            markdownPreviewContent.originalContent = content;

            // 默认显示带样式的Markdown（修复6：用marked解析）
            if (markdown) {
                markdownPreviewContent.innerHTML = marked.parse(markdown);
            } else {
                const plainText = content.replace(/<[^>]*>/g, ' ');
                markdownPreviewContent.innerHTML = marked.parse(plainText);
            }

            // 重置样式开关按钮状态
            toggleMarkdownStyleBtn.textContent = '关闭样式';
            toggleMarkdownStyleBtn.classList.remove('bg-green-500', 'hover:bg-green-600');
            toggleMarkdownStyleBtn.classList.add('bg-blue-500', 'hover:bg-blue-600');

            // 保存当前预览数据
            currentPreviewData = data;

            // 显示模态框
            previewModal.classList.remove('hidden');
            previewModal.classList.add('flex');

            // 切换到Markdown选项卡
            const htmlTab = document.querySelector('.preview-tab[data-tab="html"]');
            htmlTab.classList.remove('bg-white', 'dark:bg-gray-900', 'text-blue-600', 'dark:text-blue-400', 'border', 'border-gray-200', 'dark:border-gray-700', 'border-b-0');
            htmlTab.classList.add('text-gray-500', 'hover:text-gray-700', 'dark:text-gray-400', 'dark:hover:text-gray-300', 'hover:bg-gray-100', 'dark:hover:bg-gray-700');

            const markdownTab = document.querySelector('.preview-tab[data-tab="markdown"]');
            markdownTab.classList.add('bg-white', 'dark:bg-gray-900', 'text-blue-600', 'dark:text-blue-400', 'border', 'border-gray-200', 'dark:border-gray-700', 'border-b-0');
            markdownTab.classList.remove('text-gray-500', 'hover:text-gray-700', 'dark:text-gray-400', 'dark:hover:text-gray-300', 'hover:bg-gray-100', 'dark:hover:bg-gray-700');

            const jsonTab = document.querySelector('.preview-tab[data-tab="json"]');
            jsonTab.classList.remove('bg-white', 'dark:bg-gray-900', 'text-blue-600', 'dark:text-blue-400', 'border', 'border-gray-200', 'dark:border-gray-700', 'border-b-0');
            jsonTab.classList.add('text-gray-500', 'hover:text-gray-700', 'dark:text-gray-400', 'dark:hover:text-gray-300', 'hover:bg-gray-100', 'dark:hover:bg-gray-700');

            // 显示Markdown内容，隐藏其他内容
            htmlPreviewContent.classList.add('hidden');
            markdownPreviewContent.classList.remove('hidden');
            jsonPreviewContent.classList.add('hidden');

            // 更新按钮可见性
            toggleImagesBtn.classList.add('hidden');
            toggleMarkdownStyleBtn.classList.remove('hidden');
            copyJsonBtn.classList.add('hidden');
        }

        // 清空表格
        function clearTable() {
            resultsTbody.innerHTML = '';
            resultsData = [];
            resultCount.textContent = '0';
            tableContainer.classList.add('hidden');
            emptyState.classList.remove('hidden');
            clearResultsBtn.classList.remove('hidden');
            deleteSelectedBtn.classList.add('hidden');

            // 清空localStorage中的数据
            try {
                localStorage.removeItem('crawlerResults');
                console.log('已清空localStorage中的数据');
            } catch (error) {
                console.error('清空localStorage数据失败:', error);
            }
        }

        // 删除选中的行
        function deleteSelectedRows() {
            // 获取所有选中的复选框
            const selectedCheckboxes = document.querySelectorAll('.row-checkbox:checked');

            if (selectedCheckboxes.length === 0) {
                showStatus('info', '提示', '请先选择要删除的记录');
                return;
            }

            if (confirm(`确定要删除选中的 ${selectedCheckboxes.length} 条记录吗？`)) {
                // 收集要删除的行的唯一ID
                const uniqueIdsToDelete = [];
                selectedCheckboxes.forEach(checkbox => {
                    const uniqueId = checkbox.dataset.uniqueId;
                    uniqueIdsToDelete.push(uniqueId);
                });

                // 根据唯一ID过滤数据
                resultsData = resultsData.filter(item => {
                    return !uniqueIdsToDelete.includes(item.id);
                });

                // 保存更新后的数据到localStorage
                saveDataToLocalStorage();

                // 清空表格并重新渲染
                resultsTbody.innerHTML = '';
                resultsData.forEach((item, index) => {
                    addResultRow(item, index);
                });

                // 更新结果计数
                resultCount.textContent = resultsData.length;

                // 隐藏删除选中按钮
                deleteSelectedBtn.classList.add('hidden');

                // 重置全选复选框
                selectAllCheckbox.checked = false;

                showStatus('success', '删除成功', `已成功删除 ${selectedCheckboxes.length} 条记录`);
            }
        }

        // 更新删除选中按钮的显示状态
        function updateDeleteSelectedButtonVisibility() {
            const selectedCheckboxes = document.querySelectorAll('.row-checkbox:checked');
            if (selectedCheckboxes.length > 0) {
                deleteSelectedBtn.classList.remove('hidden');
            } else {
                deleteSelectedBtn.classList.add('hidden');
            }
        }

        // 清空按钮事件监听器
        clearResultsBtn.addEventListener('click', () => {
            if (confirm('确定要清空所有结果吗？')) {
                clearTable();
                showStatus('info', '已清空', '所有结果已清空');
            }
        });

        // 删除选中按钮事件监听器
        deleteSelectedBtn.addEventListener('click', deleteSelectedRows);

        // 全选复选框事件监听器
        selectAllCheckbox.addEventListener('change', () => {
            const rowCheckboxes = document.querySelectorAll('.row-checkbox');
            rowCheckboxes.forEach(checkbox => {
                checkbox.checked = selectAllCheckbox.checked;
            });
            updateDeleteSelectedButtonVisibility();
        });

        // 为表格添加事件委托，处理行复选框的变化
        resultsTbody.addEventListener('change', (e) => {
            if (e.target.classList.contains('row-checkbox')) {
                // 更新全选复选框状态
                const rowCheckboxes = document.querySelectorAll('.row-checkbox');
                const checkedCheckboxes = document.querySelectorAll('.row-checkbox:checked');

                if (checkedCheckboxes.length === 0) {
                    selectAllCheckbox.indeterminate = false;
                    selectAllCheckbox.checked = false;
                } else if (checkedCheckboxes.length === rowCheckboxes.length) {
                    selectAllCheckbox.indeterminate = false;
                    selectAllCheckbox.checked = true;
                } else {
                    selectAllCheckbox.indeterminate = true;
                }

                updateDeleteSelectedButtonVisibility();
            }
        });

        // 获取URL内容
        fetchBtn.addEventListener('click', async () => {
            const url = urlInput.value.trim();
            if (!url) {
                showStatus('error', '输入错误', '请输入有效的URL');
                return;
            }

            // 首先尝试获取URL对应的选择器配置
            const domainSelectors = getSelectorsForUrl(url);

            let selectors;
            if (domainSelectors) {
                // 使用域名特定的选择器
                selectors = domainSelectors;
                console.log('使用域名特定的选择器配置:', domainSelectors);
            } else {
                // 使用当前设置的选择器作为默认值
                selectors = {
                    time_selectors: getSelectorsFromContainer(timeSelectorsContainer),
                    content_selectors: getSelectorsFromContainer(contentSelectorsContainer),
                    nav_selectors: getSelectorsFromContainer(navSelectorsContainer),
                    author_selectors: getSelectorsFromContainer(authorSelectorsContainer)
                };
                console.log('使用默认选择器配置:', selectors);
            }

            // 显示加载状态覆盖层
            loadingOverlay.classList.remove('hidden');
            emptyState.classList.add('hidden');
            errorIndicator.classList.add('hidden');

            try {
                // 使用本地服务器API获取内容，包含选择器配置
                const response = await axios.post('/api', {
                    url: url,
                    selectors: selectors
                });

                if (response.data) {
                    // 处理返回的数据
                    const data = response.data;
                    let newData = [];

                    // 如果是单个结果，转换为数组
                    if (!Array.isArray(data)) {
                        newData = [data];
                    } else {
                        newData = data;
                    }

                    // 将新数据添加到现有数据中
                    resultsData = [...resultsData, ...newData];

                    // 为新数据生成唯一ID
                    newData.forEach(item => {
                        if (!item.id) {
                            // 基于采集时间和URL生成唯一ID
                            const timeStr = item.time ? item.time.toString() : Date.now().toString();
                            const urlStr = item.url || '';
                            // 使用btoa哈希生成16位ID
                            const hash = btoa(timeStr + urlStr).substring(0, 16);
                            item.id = hash;
                        }
                    });

                    // 保存数据到localStorage
                    saveDataToLocalStorage();

                    // 添加新结果到表格
                    newData.forEach((item, index) => {
                        addResultRow(item, resultsData.length - newData.length + index);
                    });

                    // 显示表格
                    tableContainer.classList.remove('hidden');

                    // 显示清空按钮
                    if (resultsData.length > 0) {
                        clearResultsBtn.classList.remove('hidden');
                    }

                    showStatus('success', '加载成功', `已成功提取 ${newData.length} 条内容，共 ${resultsData.length} 条记录`);
                } else {
                    throw new Error('无法获取有效内容');
                }
            } catch (error) {
                console.error('获取内容错误:', error);
                errorMessage.textContent = error.message || '无法连接到服务器或URL无效';
                errorIndicator.classList.remove('hidden');
                showStatus('error', '加载失败', error.message || '获取内容时发生错误');
            } finally {
                loadingOverlay.classList.add('hidden');
            }
        });

        // 设置相关函数
        // 加载设置
        function loadSettings() {
            // 尝试从localStorage加载设置
            try {
                const savedSettings = localStorage.getItem('crawlerSettings');
                if (savedSettings) {
                    const settings = JSON.parse(savedSettings);
                    renderSelectors(settings);
                } else {
                    // 如果没有保存的设置，使用默认设置
                    renderSelectors({
                        time_selectors: [],
                        content_selectors: [],
                        nav_selectors: [],
                        author_selectors: []
                    });
                }
            } catch (error) {
                console.error('加载设置失败:', error);
                showStatus('error', '加载设置失败', '无法加载保存的选择器设置');
            }
        }

        // 保存当前设置
        function saveCurrentSettings() {
            const settings = {
                time_selectors: getSelectorsFromContainer(timeSelectorsContainer),
                content_selectors: getSelectorsFromContainer(contentSelectorsContainer),
                nav_selectors: getSelectorsFromContainer(navSelectorsContainer),
                author_selectors: getSelectorsFromContainer(authorSelectorsContainer)
            };

            try {
                localStorage.setItem('crawlerSettings', JSON.stringify(settings));
                console.log('设置已保存到localStorage');
            } catch (error) {
                console.error('保存设置失败:', error);
                showStatus('error', '保存设置失败', '无法保存选择器设置');
            }
        }

        // 重置所有设置
        function resetAllSettings() {
            // 清空所有选择器输入框
            clearSelectorsContainer(timeSelectorsContainer);
            clearSelectorsContainer(contentSelectorsContainer);
            clearSelectorsContainer(navSelectorsContainer);
            clearSelectorsContainer(authorSelectorsContainer);

            // 重置预设选择器
            presetSelector.value = '';
        }

        // 渲染选择器输入框
        function renderSelectors(settings) {
            // 清空所有容器
            clearSelectorsContainer(timeSelectorsContainer);
            clearSelectorsContainer(contentSelectorsContainer);
            clearSelectorsContainer(navSelectorsContainer);
            clearSelectorsContainer(authorSelectorsContainer);

            // 渲染时间选择器
            if (settings.time_selectors && settings.time_selectors.length > 0) {
                settings.time_selectors.forEach(selector => {
                    addSelectorInput(timeSelectorsContainer, 'time_selectors', selector);
                });
            }

            // 渲染内容选择器
            if (settings.content_selectors && settings.content_selectors.length > 0) {
                settings.content_selectors.forEach(selector => {
                    addSelectorInput(contentSelectorsContainer, 'content_selectors', selector);
                });
            }

            // 渲染导航选择器
            if (settings.nav_selectors && settings.nav_selectors.length > 0) {
                settings.nav_selectors.forEach(selector => {
                    addSelectorInput(navSelectorsContainer, 'nav_selectors', selector);
                });
            }

            // 渲染作者选择器
            if (settings.author_selectors && settings.author_selectors.length > 0) {
                settings.author_selectors.forEach(selector => {
                    addSelectorInput(authorSelectorsContainer, 'author_selectors', selector);
                });
            }
        }

        // 添加选择器输入框
        function addSelectorInput(container, type, value = '') {
            const inputDiv = document.createElement('div');
            inputDiv.className = 'flex items-center mb-2';

            inputDiv.innerHTML = `
                <input type="text" 
                       class="flex-grow px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white" 
                       placeholder="输入${type.replace('_', ' ')}选择器" 
                       value="${value}">
                <button class="ml-2 px-3 py-2 bg-red-500 text-white rounded-md hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-red-500 remove-selector">
                    <i class="fas fa-trash"></i>
                </button>
            `;

            container.appendChild(inputDiv);

            // 添加删除按钮事件
            const removeBtn = inputDiv.querySelector('.remove-selector');
            removeBtn.addEventListener('click', () => {
                container.removeChild(inputDiv);
            });
        }

        // 从容器中获取选择器值
        function getSelectorsFromContainer(container) {
            const inputs = container.querySelectorAll('input[type="text"]');
            const selectors = [];

            inputs.forEach(input => {
                const value = input.value.trim();
                if (value) {
                    selectors.push(value);
                }
            });

            return selectors;
        }

        // 清空选择器容器
        function clearSelectorsContainer(container) {
            while (container.firstChild) {
                container.removeChild(container.firstChild);
            }
        }

        // 加载预设设置
        function loadPresetSettings(preset) {
            // 加载预设选择器配置
            fetch('/static/selectors.json')
                .then(response => response.json())
                .then(selectorsData => {
                    if (selectorsData[preset]) {
                        const presetSettings = selectorsData[preset];
                        renderSelectors(presetSettings);
                        showStatus('success', '预设已加载', `已加载 ${preset} 的预设选择器配置`);
                    } else {
                        showStatus('error', '加载失败', `找不到 ${preset} 的预设配置`);
                    }
                })
                .catch(error => {
                    console.error('加载预设设置失败:', error);
                    showStatus('error', '加载失败', '无法加载预设选择器配置');
                });
        }

        // 域名选择器配置相关函数
        // 加载域名选择器配置
        function loadDomainSelectors() {
            try {
                const savedDomainSelectors = localStorage.getItem('domainSelectors');
                if (savedDomainSelectors) {
                    const domainSelectors = JSON.parse(savedDomainSelectors);
                    renderDomainSelectorsTable(domainSelectors);
                } else {
                    // 如果没有保存的域名选择器，显示空表格
                    renderDomainSelectorsTable([]);
                }
            } catch (error) {
                console.error('加载域名选择器失败:', error);
                showStatus('error', '加载失败', '无法加载保存的域名选择器配置');
            }
        }

        // 渲染域名选择器表格
        function renderDomainSelectorsTable(domainSelectors) {
            const tableBody = document.getElementById('domain-selectors-tbody');
            tableBody.innerHTML = '';

            if (domainSelectors.length === 0) {
                const emptyRow = document.createElement('tr');
                emptyRow.innerHTML = `
                    <td colspan="3" class="px-6 py-4 text-center text-gray-500 dark:text-gray-400">
                        暂无域名选择器配置
                    </td>
                `;
                tableBody.appendChild(emptyRow);
                return;
            }

            domainSelectors.forEach((config, index) => {
                const row = document.createElement('tr');
                row.className = 'bg-white border-b dark:bg-gray-800 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600';

                // 格式化选择器JSON显示
                const selectorsJson = JSON.stringify(config.selectors, null, 2);

                row.innerHTML = `
                    <td class="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">
                        ${config.domain}
                    </td>
                    <td class="px-6 py-4">
                        <pre class="text-xs text-gray-500 dark:text-gray-400 overflow-x-auto max-w-xs">${selectorsJson}</pre>
                    </td>
                    <td class="px-6 py-4">
                        <button class="edit-domain-btn px-3 py-1 bg-blue-500 text-white rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 mr-2" data-index="${index}">
                            <i class="fas fa-edit"></i> 编辑
                        </button>
                        <button class="delete-domain-btn px-3 py-1 bg-red-500 text-white rounded-md hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-red-500" data-index="${index}">
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </td>
                `;

                tableBody.appendChild(row);
            });

            // 添加编辑按钮事件监听器
            document.querySelectorAll('.edit-domain-btn').forEach(btn => {
                btn.addEventListener('click', function () {
                    const index = this.getAttribute('data-index');
                    editDomainSelector(index);
                });
            });

            // 添加删除按钮事件监听器
            document.querySelectorAll('.delete-domain-btn').forEach(btn => {
                btn.addEventListener('click', function () {
                    const index = this.getAttribute('data-index');
                    deleteDomainSelector(index);
                });
            });
        }

        // 编辑域名选择器
        function editDomainSelector(index) {
            try {
                const savedDomainSelectors = localStorage.getItem('domainSelectors');
                const domainSelectors = savedDomainSelectors ? JSON.parse(savedDomainSelectors) : [];

                if (index >= 0 && index < domainSelectors.length) {
                    const config = domainSelectors[index];

                    // 填充编辑表单
                    document.getElementById('domain-input').value = config.domain;

                    // 清空并渲染选择器输入框
                    clearSelectorsContainer(document.getElementById('edit-time-selectors-container'));
                    clearSelectorsContainer(document.getElementById('edit-content-selectors-container'));
                    clearSelectorsContainer(document.getElementById('edit-nav-selectors-container'));
                    clearSelectorsContainer(document.getElementById('edit-author-selectors-container'));

                    // 渲染编辑表单中的选择器
                    if (config.selectors.time_selectors && config.selectors.time_selectors.length > 0) {
                        config.selectors.time_selectors.forEach(selector => {
                            addEditSelectorInput(document.getElementById('edit-time-selectors-container'), 'time_selectors', selector);
                        });
                    }

                    if (config.selectors.content_selectors && config.selectors.content_selectors.length > 0) {
                        config.selectors.content_selectors.forEach(selector => {
                            addEditSelectorInput(document.getElementById('edit-content-selectors-container'), 'content_selectors', selector);
                        });
                    }

                    if (config.selectors.nav_selectors && config.selectors.nav_selectors.length > 0) {
                        config.selectors.nav_selectors.forEach(selector => {
                            addEditSelectorInput(document.getElementById('edit-nav-selectors-container'), 'nav_selectors', selector);
                        });
                    }

                    if (config.selectors.author_selectors && config.selectors.author_selectors.length > 0) {
                        config.selectors.author_selectors.forEach(selector => {
                            addEditSelectorInput(document.getElementById('edit-author-selectors-container'), 'author_selectors', selector);
                        });
                    }

                    // 保存当前编辑的索引
                    document.getElementById('domain-selector-modal').setAttribute('data-edit-index', index);

                    // 显示编辑模态框
                    document.getElementById('domain-selector-modal').classList.remove('hidden');
                }
            } catch (error) {
                console.error('编辑域名选择器失败:', error);
                showStatus('error', '编辑失败', '无法编辑域名选择器配置');
            }
        }

        // 删除域名选择器
        function deleteDomainSelector(index) {
            if (confirm('确定要删除这个域名选择器配置吗？')) {
                try {
                    const savedDomainSelectors = localStorage.getItem('domainSelectors');
                    const domainSelectors = savedDomainSelectors ? JSON.parse(savedDomainSelectors) : [];

                    if (index >= 0 && index < domainSelectors.length) {
                        domainSelectors.splice(index, 1);

                        // 保存更新后的配置
                        localStorage.setItem('domainSelectors', JSON.stringify(domainSelectors));

                        // 重新渲染表格
                        renderDomainSelectorsTable(domainSelectors);

                        showStatus('success', '删除成功', '域名选择器配置已删除');
                    }
                } catch (error) {
                    console.error('删除域名选择器失败:', error);
                    showStatus('error', '删除失败', '无法删除域名选择器配置');
                }
            }
        }

        // 添加编辑表单的选择器输入框
        function addEditSelectorInput(container, type, value = '') {
            const inputDiv = document.createElement('div');
            inputDiv.className = 'flex items-center mb-2';

            inputDiv.innerHTML = `
                <input type="text" 
                       class="flex-grow px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white" 
                       placeholder="输入${type.replace('_', ' ')}选择器" 
                       value="${value}">
                <button class="ml-2 px-3 py-2 bg-red-500 text-white rounded-md hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-red-500 remove-edit-selector">
                    <i class="fas fa-trash"></i>
                </button>
            `;

            container.appendChild(inputDiv);

            // 添加删除按钮事件
            const removeBtn = inputDiv.querySelector('.remove-edit-selector');
            removeBtn.addEventListener('click', () => {
                container.removeChild(inputDiv);
            });
        }

        // 保存域名选择器配置
        function saveDomainSelector() {
            try {
                const domain = document.getElementById('domain-input').value.trim();
                if (!domain) {
                    showStatus('error', '保存失败', '请输入域名');
                    return;
                }

                // 获取选择器配置
                const selectors = {
                    time_selectors: getSelectorsFromContainer(document.getElementById('edit-time-selectors-container')),
                    content_selectors: getSelectorsFromContainer(document.getElementById('edit-content-selectors-container')),
                    nav_selectors: getSelectorsFromContainer(document.getElementById('edit-nav-selectors-container')),
                    author_selectors: getSelectorsFromContainer(document.getElementById('edit-author-selectors-container'))
                };

                // 获取当前编辑的索引
                const editIndex = document.getElementById('domain-selector-modal').getAttribute('data-edit-index');

                // 获取现有的域名选择器配置
                const savedDomainSelectors = localStorage.getItem('domainSelectors');
                const domainSelectors = savedDomainSelectors ? JSON.parse(savedDomainSelectors) : [];

                if (editIndex !== null && editIndex !== '') {
                    // 编辑现有配置
                    const index = parseInt(editIndex);
                    if (index >= 0 && index < domainSelectors.length) {
                        domainSelectors[index] = {
                            domain: domain,
                            selectors: selectors
                        };
                    }
                } else {
                    // 添加新配置
                    domainSelectors.push({
                        domain: domain,
                        selectors: selectors
                    });
                }

                // 保存配置
                localStorage.setItem('domainSelectors', JSON.stringify(domainSelectors));

                // 重新渲染表格
                renderDomainSelectorsTable(domainSelectors);

                // 关闭编辑模态框
                document.getElementById('domain-selector-modal').classList.add('hidden');

                // 重置编辑表单
                resetEditForm();

                showStatus('success', '保存成功', '域名选择器配置已保存');
            } catch (error) {
                console.error('保存域名选择器失败:', error);
                showStatus('error', '保存失败', '无法保存域名选择器配置');
            }
        }

        // 重置编辑表单
        function resetEditForm() {
            document.getElementById('domain-input').value = '';
            clearSelectorsContainer(document.getElementById('edit-time-selectors-container'));
            clearSelectorsContainer(document.getElementById('edit-content-selectors-container'));
            clearSelectorsContainer(document.getElementById('edit-nav-selectors-container'));
            clearSelectorsContainer(document.getElementById('edit-author-selectors-container'));
            document.getElementById('domain-selector-modal').removeAttribute('data-edit-index');
        }

        // 添加新域名选择器配置
        function addNewDomainSelector() {
            // 重置编辑表单
            resetEditForm();

            // 显示编辑模态框
            document.getElementById('domain-selector-modal').classList.remove('hidden');
        }

        // 从URL中提取域名
        function extractDomainFromUrl(url) {
            try {
                const urlObj = new URL(url);
                return urlObj.hostname;
            } catch (error) {
                console.error('提取域名失败:', error);
                return '';
            }
        }

        // 根据URL获取对应的选择器配置
        function getSelectorsForUrl(url) {
            try {
                const domain = extractDomainFromUrl(url);
                if (!domain) {
                    return null;
                }

                const savedDomainSelectors = localStorage.getItem('domainSelectors');
                const domainSelectors = savedDomainSelectors ? JSON.parse(savedDomainSelectors) : [];

                // 查找匹配的域名配置
                for (const config of domainSelectors) {
                    if (domain === config.domain || domain.endsWith('.' + config.domain)) {
                        return config.selectors;
                    }
                }

                return null;
            } catch (error) {
                console.error('获取URL选择器失败:', error);
                return null;
            }
        }

        // 添加域名选择器相关的事件监听器
        document.addEventListener('DOMContentLoaded', function () {
            // 页面初始化时加载域名选择器配置
            loadDomainSelectors();

            // 设置按钮点击事件 - 加载域名选择器
            document.getElementById('settings-btn').addEventListener('click', function () {
                loadDomainSelectors();
            });

            // 添加域名配置按钮点击事件
            document.getElementById('add-domain-selector').addEventListener('click', function () {
                addNewDomainSelector();
            });

            // 保存域名配置按钮点击事件
            document.getElementById('save-domain-selector').addEventListener('click', function () {
                saveDomainSelector();
            });

            // 取消编辑按钮点击事件
            document.getElementById('cancel-domain-selector').addEventListener('click', function () {
                document.getElementById('domain-selector-modal').classList.add('hidden');
                resetEditForm();
            });

            // 编辑表单中的添加选择器按钮事件
            document.getElementById('edit-add-time-selector').addEventListener('click', function () {
                addEditSelectorInput(document.getElementById('edit-time-selectors-container'), 'time_selectors');
            });

            document.getElementById('edit-add-content-selector').addEventListener('click', function () {
                addEditSelectorInput(document.getElementById('edit-content-selectors-container'), 'content_selectors');
            });

            document.getElementById('edit-add-nav-selector').addEventListener('click', function () {
                addEditSelectorInput(document.getElementById('edit-nav-selectors-container'), 'nav_selectors');
            });

            document.getElementById('edit-add-author-selector').addEventListener('click', function () {
                addEditSelectorInput(document.getElementById('edit-author-selectors-container'), 'author_selectors');
            });

            // 预设选择器下拉菜单事件
            document.getElementById('edit-preset-selector').addEventListener('change', function () {
                const presetValue = this.value;
                if (presetValue) {
                    try {
                        const presetConfig = JSON.parse(presetValue);

                        // 清空现有选择器
                        clearSelectorsContainer(document.getElementById('edit-time-selectors-container'));
                        clearSelectorsContainer(document.getElementById('edit-content-selectors-container'));
                        clearSelectorsContainer(document.getElementById('edit-nav-selectors-container'));
                        clearSelectorsContainer(document.getElementById('edit-author-selectors-container'));

                        // 添加预设选择器
                        if (presetConfig.time_selectors && presetConfig.time_selectors.length > 0) {
                            presetConfig.time_selectors.forEach(selector => {
                                addEditSelectorInput(document.getElementById('edit-time-selectors-container'), 'time_selectors', selector);
                            });
                        }

                        if (presetConfig.content_selectors && presetConfig.content_selectors.length > 0) {
                            presetConfig.content_selectors.forEach(selector => {
                                addEditSelectorInput(document.getElementById('edit-content-selectors-container'), 'content_selectors', selector);
                            });
                        }

                        if (presetConfig.nav_selectors && presetConfig.nav_selectors.length > 0) {
                            presetConfig.nav_selectors.forEach(selector => {
                                addEditSelectorInput(document.getElementById('edit-nav-selectors-container'), 'nav_selectors', selector);
                            });
                        }

                        if (presetConfig.author_selectors && presetConfig.author_selectors.length > 0) {
                            presetConfig.author_selectors.forEach(selector => {
                                addEditSelectorInput(document.getElementById('edit-author-selectors-container'), 'author_selectors', selector);
                            });
                        }
                    } catch (error) {
                        console.error('加载预设选择器失败:', error);
                        showStatus('error', '加载失败', '无法加载预设选择器配置');
                    }
                }
            });
        });
    </script>
</body>

</html>